﻿using UnityEngine;
using System.Collections;
using ProgressBar;

public class CVRInfoItem : MonoBehaviour {

	public int m_nID;
	public UIScrollView m_HScrollView;
	public UIScrollView m_VScrollView;
	public GameObject	m_WaitingBar;
	public UITexture 	m_Circle;
	public UILabel		m_ProgressLabel;
	Vector3 			m_MousePos;
	public bool			m_bLoaded;
	WWW					www;
	float 				progress;

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		m_Circle.transform.RotateAround (Vector3.back, Time.deltaTime * 2);
		if(www != null)
			m_ProgressLabel.text = ((int)(www.progress * 100)).ToString () + " %";
		
		if (m_bLoaded)
			m_WaitingBar.gameObject.SetActive(false);

		UITexture tex = GetComponent<UITexture> ();
		m_WaitingBar.transform.localPosition = new Vector2 (0, (tex.height - Screen.height) / 2 + 90);
	}

	void OnPress(bool pressed)
	{
		if (pressed)
			m_MousePos = Input.mousePosition;
		
		if(!pressed) {
			float xDif = Mathf.Abs(Input.mousePosition.x - m_MousePos.x);
			float yDif = Mathf.Abs(Input.mousePosition.y - m_MousePos.y);

			if(xDif > yDif && CVRInfoScene.Instance.ITEM_COUNT > 1) {
				if(Input.mousePosition.x - m_MousePos.x > 10)
					CVRInfoScene.Instance.SelectItem(false);
				else if(m_MousePos.x - Input.mousePosition.x > 10)
					CVRInfoScene.Instance.SelectItem(true);
				else
					m_HScrollView.GetComponent<UICenterOnChild>().CenterOn(transform);
			}
		}

		m_VScrollView.Press (pressed);
	}

	void OnDrag(Vector2 delta)
	{
		if (Mathf.Abs (delta.x) > Mathf.Abs (delta.y) && CVRInfoScene.Instance.ITEM_COUNT > 1)
			m_HScrollView.Drag ();
		else if (delta.y > 0 || m_VScrollView.transform.localPosition.y > -40)
			m_VScrollView.Drag ();
	}

	public IEnumerator SetTexture()
	{
		UITexture texture = GetComponent<UITexture> ();
		VR_AR.VR_INFO vrInfo = JsonDataRead.Instance.vrHighItems [JsonDataRead.Instance.curHighVRID];
		Texture tex = JsonDataRead.Instance.FindTextureByUrl (vrInfo.vrImages[m_nID].introImageFilePath);

		if (tex == null) {
			www = new WWW (JsonDataRead.Instance.DataPath + vrInfo.vrImages[m_nID].introImageFilePath);
			yield return www;
			texture.mainTexture = www.texture;
			JsonDataRead.Instance.AddTexture(vrInfo.vrImages[m_nID].introImageFilePath, www.texture);
			m_bLoaded = true;
		} else {
			texture.mainTexture = tex;
			m_bLoaded = true;
		}
	}
}